package com.shiliuzi.www.controller.exception;

import com.shiliuzi.www.common.Code;
import com.shiliuzi.www.common.Result;
import com.shiliuzi.www.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class ExceptionController {

    /**
     * 全局异常处理器
     * @param e
     * @return
     */
    @ExceptionHandler(GlobalException.class)
    public Result globalException (Exception e) {
        log.error("异常是："+e.getMessage());
        return Result.error(Code.SYS_ERR, e.getMessage());
    }

    /**
     * 参数校验异常处理器
     * @param e
     * @return
     */
    @ExceptionHandler(value = {BindException.class, ValidationException.class,MethodArgumentNotValidException.class})
    public Result validException (Exception e) {
        String message = new String();
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            message = exception.getBindingResult().getAllErrors().stream().
                    map(ObjectError::getDefaultMessage).
                    collect(Collectors.joining("; "));
        } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException exception = (ConstraintViolationException) e;
            message = exception.getConstraintViolations().stream().
                    map(ConstraintViolation::getMessage).
                    collect(Collectors.joining("; "));
        } else if (e instanceof BindException) {
            BindException exception = (BindException) e;
            message = exception.getAllErrors().stream().
                    map(ObjectError::getDefaultMessage).
                    collect(Collectors.joining("; "));
        }
        return Result.error(Code.BUE_PARAM_ERR, message);
    }
}
